package com.example.task.socket;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.ActionMode;

import com.example.task.R;
import com.example.task.adapter.AppDetailListViewBaseAdapter;
import com.example.task.bean.Recode;
import com.example.task.bean.SocketUser;
import com.example.task.sqlite.dao.RecodeDao;


public class SocketActivity extends AppCompatActivity {
    //IP地址和端口号
    public static String IP_ADDRESS = "106.54.189.155";
//    public static String IP_ADDRESS = "192.168.51.235";
    public static int PORT = 9999;
    //三个控件
    EditText et_message = null;  //需要发送的内容
    Button bt_send = null;   //发送
    TextView tv_reply = null;   //服务器回复的消息
    //handler
    Handler handler = null;
    Socket socket = null;
    //socket连接状态
    Boolean isConnect;
    Boolean isReceive;

    RecodeDao recodeDao;

    ListView listView;
    List<Map<String,Object>> lists;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket2);

        listView = findViewById(R.id.ListView);
        listView.setSelection(listView.getBottom());
        recodeDao = new RecodeDao(this);
        lists = new ArrayList<>();

//        Button button = findViewById(R.id.Button);
//        button.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                new RecodeDao(SocketActivity.this).delete();
//                tv_reply.setText("");
//            }
//        });

        Intent intent = getIntent();
        //从Intent中取出Bundle
        Bundle bundle = intent.getExtras();
        //获取FunPerson里的数据数据
        assert bundle != null;
        SocketUser user = (SocketUser)bundle.getSerializable("SocketUser");
        assert user != null;


        et_message = findViewById(R.id.et_message);
        bt_send = findViewById(R.id.bt_connect);
        tv_reply = findViewById(R.id.tv_reply);
//        recodeDao.delete();
        //数据库加载
        List<Recode> list = recodeDao.select();
        for(Recode recode:list){
            Map<String,Object> map = new HashMap();
            String str = recode.getData();
            System.out.println("str"+str);
            if(str.length() <= "2022-06-28 01:59:02:李四(student):".length()){
                continue;
            }
            String time = str.split(":")[0]+":"+str.split(":")[1]+":"+str.split(":")[2];
            String role = str.split(":")[3];
            String data = str.split(":")[4];


            if((user.getRoleName()+"("+user.getRole()+")").equals(role)){
                map.put("name2",role);
                map.put("data2",data);
                map.put("image2",R.drawable.img_wyu);
            }else{
                map.put("name1",role);
                map.put("data1",data);
                map.put("image1",R.drawable.img_wyu);
            }
//            System.out.println(time+role+data);
//            map.put("time",time);


            lists.add(map);
//            tv_reply.append(str);
//            tv_reply.append("\n");
        }
        if(lists.size() != 0){
            AppDetailListViewBaseAdapter adapter = new AppDetailListViewBaseAdapter(lists,this);
//        SimpleAdapter adapter = new SimpleAdapter(this,lists,R.layout.activity_socket_item,
//                new String[]{"image1","role1","data1","role2","data2","image2"},
////                new int[]{R.id.ImageView1,R.id.name1,R.id.data1});
//        new int[]{R.id.ImageView1,R.id.name1,R.id.data1,R.id.name2,R.id.data2,R.id.ImageView2});
            listView.setAdapter(adapter);
            listView.setSelection(listView.getBottom());
        }



        //todo 看这里啊喂!!!
        bt_send.setOnClickListener(v -> {
            new Send(et_message.getText().toString()).start();
            et_message.setText("");
//            System.out.println("已发送");
        });

        handler = new Handler(msg -> {
            Bundle b = msg.getData();  //获取消息中的Bundle对象
            String str = b.getString("data");  //获取键为data的字符串的值
//            String time = str.split(":")[0]+":"+str.split(":")[1]+":"+str.split(":")[2];
            String role = str.split(":")[3];
            String data = str.split(":")[4];

            Map<String,Object> map = new HashMap();
            if((user.getRoleName()+"("+user.getRole()+")").equals(role)){
                map.put("name2",role);
                map.put("data2",data);
                map.put("image2",R.drawable.img_wyu);
            }else{
                map.put("name1",role);
                map.put("data1",data);
                map.put("image1",R.drawable.img_wyu);
            }

            lists.add(map);

            AppDetailListViewBaseAdapter adapter2 = new AppDetailListViewBaseAdapter(lists,this);

//            SimpleAdapter adapter2 = new SimpleAdapter(this,lists,R.layout.activity_socket_item,
//                    new String[]{"image1","role1","data1","role2","data2","image2"},
////                new int[]{R.id.ImageView1,R.id.name1,R.id.data1});
//                    new int[]{R.id.ImageView1,R.id.name1,R.id.data1,R.id.name2,R.id.data2,R.id.ImageView2});
////        new int[]{R.id.ImageView1,R.id.name1,R.id.data1,R.id.name2,R.id.data2,R.id.ImageView2});
            listView.setAdapter(adapter2);
            listView.setSelection(listView.getBottom());

//            tv_reply.append(str);
//            tv_reply.append("\n");
            return false;
        });

        //连接服务器
        Connect connect = new Connect();
        connect.start();
        try {
            connect.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        String roleName = user.getRoleName();
        String activityId = user.getActivityId();
        String role = user.getRole();
        //todo 看这里啊喂
        //role: 角色，用于分配不同权限，"student"和"teacher"两个值
        //roleName: 用户名，用于标识聊天室的人
        //activityName: 活动名称，用于分配不太聊天室
        new Send(role+"&"+roleName+"&"+activityId).start();

    }

    class Connect extends Thread{
        @Override
        public void run() {
            try {
                socket = new Socket(IP_ADDRESS,PORT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            isConnect=true;
            isReceive=true;
            Receive receive = new Receive(socket);
            receive.start();
            System.out.println("----connected success----");
        }
    }
    class Receive extends Thread{

        private InputStream inputStream=null;
        Receive(Socket socket){
            //初始化输入流
            try {
                inputStream = socket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            while (isReceive){
                byte[] buffer = new byte[512];
                try {
                    inputStream.read(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                    break;
                }
                String str = null;
                try {
                    str = new String(buffer,"UTF-8").trim();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                recodeDao.add(new Recode(str));

                Message msg = new Message();
                Bundle b = new Bundle();
                b.putString("data", str);
                msg.setData(b);
                System.out.println("已发送");
                handler.sendMessage(msg);
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            finish();
        }
    }

    //新建一个子线程，实现socket通信
    class Send extends Thread {
        String message;

        public Send(String msg) {
            this.message = msg;
        }

        @Override
        public void run() {

            try {

                byte [] sendBuffer = null;

                //可替代为接收输入框的字符串.getBytes
                sendBuffer = message.getBytes("UTF-8");

                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(sendBuffer);

                outputStream.flush();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onSupportActionModeFinished(@NonNull ActionMode mode) {
        super.onSupportActionModeFinished(mode);
        System.out.println("finish");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 是否触发按键为back键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            System.out.println("点击返回键");
            outSocket();
            return true;
        } else {// 如果不是back键正常响应
            return super.onKeyDown(keyCode, event);
        }
    }

    //退出socket
    public void outSocket(){
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
